package com.youlai.system.controller;

import com.youlai.common.result.PageResult;
import com.youlai.common.result.Result;
import com.youlai.system.entity.SysEmpEntity;
import com.youlai.system.model.query.OrgPageQuery;
import com.youlai.common.plugin.dupsubmit.annotation.PreventDuplicateSubmit;
import com.youlai.system.services.SysEmpService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;

@Tag(name = "员工管理接口(jpa例子)")
@RestController
@RequestMapping("/api/v1/emp")
@RequiredArgsConstructor
public class SysEmpController {

    private final SysEmpService service;

    @Operation(summary = "分页列表")
    @GetMapping("/page")
    public PageResult<SysEmpEntity> getPage(@ParameterObject OrgPageQuery queryParams) {
        Page<SysEmpEntity> page = service.getPage(queryParams);
        List<SysEmpEntity> list = new LinkedList<>();
        for(SysEmpEntity o:page){
            list.add(o);
        }
        return PageResult.success(list, page.getTotalElements());
    }

    @Operation(summary = "获取表单数据")
    @GetMapping("/{id}/form")
    public Result<SysEmpEntity> getForm(
            @Parameter(description ="字典ID") @PathVariable Long id
    ) {
        SysEmpEntity sysOrg = service.findById(id);
        return Result.success(sysOrg);
    }

    @Operation(summary = "新增")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:org:add')")
    @PreventDuplicateSubmit
    public Result saveOrUpdate(@RequestBody SysEmpEntity form) {
        service.saveOrUpdate(form);
        return Result.judge(true);
    }

    @Operation(summary = "修改")
    @PutMapping("/{id}")
    @PreAuthorize("@ss.hasPerm('sys:org:edit')")
    public Result update(@PathVariable Long id, @RequestBody SysEmpEntity form) {
        form.setId(id);
        service.saveOrUpdate(form);
        return Result.judge(true);
    }

    @Operation(summary = "删除")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:org:del')")
    public Result deleteByIds(@Parameter(description ="主键ID，多个以英文逗号(,)拼接") @PathVariable String ids) {
        boolean result = service.deleteAllById(ids);
        return Result.judge(result);
    }

}
